import 'dart:async';
import 'dart:convert';
import 'dart:ui' as ui;
import 'package:bookshelf/event/icr_bind_event.dart';
import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/util/timer_manager.dart';
import 'package:bookshelf/widget/icr_bind_dialog.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/reader_entity.dart';
import '../main.dart';
import '../serial/three_to_one_manager.dart';
import '../widget/app_bar.dart';
import '../util/toast_util.dart';
import '../widget/circle_progress_widget.dart';
import '../widget/clipper.dart';

class Mine extends StatefulWidget {
  const Mine({Key? key}) : super(key: key);

  @override
  State<Mine> createState() => _MineState();
}

class _MineState extends State<Mine> {

  final RxList<ReaderCurrentBorrowList> _list = RxList();
  late ReaderEntity readerEntity;

  RxBool isEmpty = RxBool(false);
  RxBool pause = RxBool(false);
  RxBool initialize = RxBool(false);
  late List<CameraDescription> _cameras;
  CameraController? controller;
  Timer? _timer;
  var countTime = 120;
  final GlobalKey _globalKey = GlobalKey();

  ThreeToOneManager manager = ThreeToOneManager();
  StreamSubscription? icrSubscription;

  RxnString icrNum = RxnString(null);


  @override
  initState() {
    super.initState();

    readerEntity = Get.arguments;
    if(readerEntity.icrNo != null){
      icrNum.value = readerEntity.icrNo;
    }

    if(readerEntity.currentBorrowList != null ){
      _list.addAll(readerEntity.currentBorrowList!);
    }

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        _disposeCamera();
        currentTask.clear();
        timer.cancel();
        manager.setMode(Mode.none);
        Get.until((route) => route.isFirst);
      });
    });

    icrSubscription = eventFactory.on<IcrBindEvent>().listen((event) async {
      if(Get.isDialogOpen != null && Get.isDialogOpen!){
        Get.back();
      }
      // IcrBindDialog().bindDialog((id) async {
        var data = await bind(currentTask.uid, event.icr);
        if(data){
          // icrNum.value = id;
          toastWarn('绑定成功');
        }else{
          toastWarn('绑定失败');
        }
      // });

    });

    _checkFace();

  }

  _title(){
    return Container(
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              _disposeCamera();
              currentTask.clear();
              timer.cancel();
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,),
          ),
          Text("我的列表",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
          Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))
        ],
      )
    );
  }



  _itemBuilder(index){
    var item = _list[index];
    return Container(
        padding: EdgeInsets.only(top: 16.h,bottom: 16.h,left: 26.w,right: 26.w),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/borrow_item_bg.png",
            ),
          ),
        ),
        // alignment: Alignment.center,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Image.asset("assets/images/item_icon.png",width: 10.w,fit: BoxFit.fitWidth,),
                SizedBox(width: 290.w,child: Text(' ${item.bookTitle}',style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp)),),
                if(item.status==2)...[
                  Text('续借成功',style: TextStyle(color: const Color.fromRGBO(19, 136, 8, 1),fontSize: 10.sp))
                ]
              ],
            ),
            SizedBox(height: 5.h,),
            const Divider(height: 1.0,color: Colors.grey,),
            SizedBox(height: 10.h,),
            Text('图书编号：${item.bookNo}',style: TextStyle(color: Colors.grey,fontSize: 8.sp)),
            Text('归还时间：${item.readyReturnDate}',style: TextStyle(color: Colors.grey,fontSize: 8.sp)),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(height:30.h,alignment: Alignment.center,child: Text(item.error??'',style: TextStyle(color: Colors.red,fontSize: 8.sp),textAlign: TextAlign.center,),),
                if(item.status==0)...[
                  InkWell(
                      onTap: () async {
                        var result = await bookBorrowAgain(currentTask.uid,item.bookNo);
                        if(result.$1 ==200){
                          setState(() {
                            tts.speak('续借成功');
                            item.status = 2;
                            item.readyReturnDate = result.$2.readyReturnDate;
                          });

                        }else{
                          setState(() {
                            tts.speak('续借失败');
                            item.error = result.$2;
                            item.status = 1;
                          });
                        }
                      },
                      child: Align(alignment: Alignment.centerRight,child: Image.asset("assets/images/borrow_again.png",width: 60.w,fit: BoxFit.fitWidth,),)
                  )
                ]
              ],
            ),
          ],
        )
    );
  }

  _openCamera() async {
    _cameras = await availableCameras();
    controller = CameraController(_cameras[0], ResolutionPreset.high);
    controller!.initialize().then((_) {
      initialize.value = true;
      _start();
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            toastError('Camera CameraAccessDenied');
            break;
          default:
            toastError('camera error');
            _disposeCamera();
            break;
        }
      }
    });
  }

  _disposeCamera(){
    _timer?.cancel();
    _timer = null;
    initialize.value = false;
    try{
      controller?.dispose();
      controller = null;
    }catch(e){
      print(e);
    }
  }


  @override
  void dispose() {
    icrSubscription?.cancel();
    icrSubscription = null;
    _disposeCamera();
    super.dispose();
  }

  _start(){
    countTime = settingEntity.actionTime??120;
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (countTime <= 0) {
        if(_timer!=null){
          _timer!.cancel();
          _timer = null;
        }
        return;
      }
      countTime = countTime-3;
      // _computeTakePicture();
      _widgetToImage();
    });
  }

  // _computeTakePicture() {
  //   if (controller != null) {
  //     controller!.takePicture().then((file){
  //       file.readAsBytes().then((bytes){
  //         String base64 = base64Encode(bytes);
  //         String base64Image = "data:image/png;base64,$base64";
  //         faceAdd(currentTask.uid,currentTask.uName,base64Image).then((data){
  //           if(data.$1 ){
  //             if(controller != null){
  //               toastWarn('认证成功');
  //               tts.speak("认证成功");
  //               _timer?.cancel();
  //               _timer = null;
  //
  //               controller!.pausePreview().then((value) {
  //                 pause.value = true;
  //               });
  //             }
  //           }else{
  //             toastWarn('${data.$2}');
  //           }
  //         });
  //         File f = File.fromUri(Uri.file(file.path));
  //         f.delete();
  //       });
  //     });
  //   }
  // }


  // _getToken() async {
  //   if(settingEntity.face == 'kd'){
  //     // await kdToken();
  //     // _checkFace();
  //   }else{
  //     _checkFace();
  //   }
  // }

  _checkFace() {
    if(settingEntity.face == 'xy'){
      faceQuery(readerEntity.no!).then((value){
        isEmpty.value = value;
      });
     // kdFaceQuery(readerEntity.no!).then((value){
     //   isEmpty.value = value;
     // });
    }

  }

  _widgetToImage() {
    RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    render.toImage().then((image){
      image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
        if(byteData != null){
          String base64 = base64Encode(byteData.buffer.asUint8List());
          String base64Image = "data:image/png;base64,$base64";
          _addFace(base64Image);
        }
      });
    });
  }

  _addFace(base64Image){
    if(settingEntity.face == 'kd'){
      // kdFaceAdd(currentTask.uid,base64Image).then((data){
      //   if(data.$1 ){
      //     if(controller != null){
      //       toastWarn('认证成功');
      //       tts.speak("认证成功");
      //       _timer?.cancel();
      //       _timer = null;
      //       controller!.pausePreview().then((value) {
      //         pause.value = true;
      //       });
      //     }
      //   }else{
      //     toastWarn('${data.$2}');
      //   }
      // });
    }else{
      faceAdd(currentTask.uid,currentTask.uName,base64Image).then((data){
        if(data.$1 ){
          if(controller != null){
            toastWarn('认证成功');
            tts.speak("认证成功");
            _timer?.cancel();
            _timer = null;
            controller!.pausePreview().then((value) {
              pause.value = true;
            });
          }
        }else{
          toastWarn('${data.$2}');
        }
      });
    }

  }


  _booksContainer(){
    return Obx(() => initialize.value?
      Expanded(child: Stack(
        children: [
          Positioned(
            left: 0,
            right: 0,
            top: 80.h,
            child: Align(
              child:
              RepaintBoundary(
                key: _globalKey,
                child:  ClipOval(
                  clipper: ClipperOvalPath(240.w,0),
                  child:  Transform.scale(
                    scale: 0.8,
                    child: Transform.translate(offset: Offset(0,-230.h),
                      child: RotatedBox(
                        quarterTurns: settingEntity.rotate??2,
                        child: AspectRatio(
                            aspectRatio: 0.56,
                            child: CameraPreview(controller!)
                        ),
                      ),),
                  ),
                ),
              )
            ),
          ),
          Positioned(
              left: 130.w,
              right: 130.w,
              top: 370.h,
              child: InkWell(
                onTap: (){
                  initialize.value = false;
                  _disposeCamera();
                  if(pause.value){
                    _checkFace();
                  }
                },
                child: Image.asset("assets/images/camera_${pause.value?'confirm':'cancel'}.png",),
              )
          ),
          if(pause.value)...[
            Positioned(
                left: 0,
                right: 0,
                top: 420.h,
                child: InkWell(
                  child: Align(child: Text('照片不满意？重拍',style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),),
                  onTap: () async {
                    if(controller != null){
                      pause.value = false;
                      controller!.resumePreview();
                      _start();
                    }else{
                      toastWarn('camera error');
                    }
                  },
                )
            ),
          ]
        ],
      )):
      Expanded(child: ListView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: _list.length,
      ))
    );
  }

  _person(){
    return Container(
        margin: EdgeInsets.only(left: 8.w,right: 8.w),
        height: 120.h,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/person_info_bg.png",
            ),
          ),
        ),
        child: Stack(
          alignment: AlignmentDirectional.centerStart,
          children: [
            Positioned(left:40.w,child: Image.asset("assets/images/head.jpg",width: 80.w,fit: BoxFit.fitWidth,),),
            Positioned(left:130.w,top:28.h,child: Text("${currentTask.uName}   ",style: TextStyle(color: Colors.blue,fontSize: 12.sp,fontWeight: FontWeight.bold),)),
            Positioned(left:130.w,top:45.h,child: Text("读者证号:${currentTask.uid}",style: TextStyle(color: Colors.blue,fontSize: 10.sp),)),
            Positioned(left:130.w,top:62.h,child:
            InkWell(
              onTap: (){
                IcrBindDialog().icrDialog();
              },
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text("身份证:  ",style: TextStyle(color: Colors.blue,fontSize: 10.sp),),
                  // Text("读者证号:${currentTask.uid}",style: TextStyle(color: Colors.blue,fontSize: 10.sp),),
                  Image.asset("assets/images/icr_bind.png",width: 34.w,fit: BoxFit.fitWidth,),
                ],
              ),
            ),
            ),
            if(settingEntity.face != 'kd')...[
              Positioned(left:130.w,top:80.h,
                child: InkWell(
                    onTap: (){
                      if(controller == null){
                        _openCamera();
                      }
                    },
                    child: Obx(() => isEmpty.value?
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("人脸登陆:已注册  ",style: TextStyle(color: Colors.blue,fontSize: 10.sp),),
                        Image.asset("assets/images/camera_change.png",width: 34.w,fit: BoxFit.fitWidth,),
                      ],
                    ):
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("人脸登陆:未注册  ",style: TextStyle(color: Colors.blue,fontSize: 10.sp),),
                        Image.asset("assets/images/camera_register.png",width: 34.w,fit: BoxFit.fitWidth,),
                      ],
                    ),
                    )
                ),
              )
            ],
            Positioned(
                right: 30.w,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    CircleProgress(size: 60.w,strokeWidth: 3.w,percent: readerEntity.currentBorrowCount!/readerEntity.limitCount!,color: Colors.blue,),
                    Container(
                      width: 50.w,
                      height: 50.w,
                      decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.all(Radius.circular(25.r)),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text('${readerEntity.currentBorrowCount}/${readerEntity.limitCount}',style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),),
                          Text('借阅数量',style: TextStyle(color: Colors.white,fontSize: 6.sp),)
                        ],
                      ),
                    )
                  ],
                )
            ),
          ],
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(),
            _title(),
            _person(),
            _booksContainer(),

          ],
        ),
      ),
    );
  }
}

